//
//  MainViewController.m
//  Stream
//
//  Copyright © 2016年 showshaw. All rights reserved.
//
//  首页

#import "MainViewController.h"
#import "MainCollectionViewCell.h"
#import "MainCollectionViewModel.h"
#import "UIButton+WebCache.h"
#import "SlideModel.h"
#import "XXWebViewController.h"
#import "FunctionItem.h"
//#import "MainHeaderCollectionCell.h"
#import "CollectionHeaderView.h"
#import "SlideNavigationController.h"
#import "LeftMenuViewController.h"
NS_ENUM(NSInteger,CellState){
    CellStateNormal = 0,
    CellStateDelete = 1
};


static NSString* const WeatherAPIKey = @"ade93ea486e5d4ced4bc8552978d17e6";
static NSString* const WeatherURL = @"http://apis.baidu.com/apistore/weatherservice/weather";

@interface MainViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MainCollectionViewCellDelegate,CollectionHeaderViewDelegate,SlideNavigationControllerDelegate,LeftMenuViewControllerDelegate>


/**
 *  Collection View
 */
@property (nonatomic,strong) UICollectionView* collectionView;
/**
 *  Header View
 */
@property (nonatomic,strong) CollectionHeaderView* headerView;
/**
 *  Item
 */
@property (nonatomic,strong) NSMutableArray* dataArray;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [Utils checkLoginStatus:self];
    
    [self setupView];
    
    [self setupBeginData];
    
    [self.collectionView reloadData];
    
    //设置左侧滑动范围
    [SlideNavigationController sharedInstance].portraitSlideOffset = 120.0f;
}
#pragma mark - Left MenuView Delegate
-(void)leftMenuViewDidClickedFindPassword:(UIButton *)sender
{
    [MBProgressHUD showMessage:@"找回密码" hide:YES];
}

-(void)leftMenuViewDidClickedAbout:(UIButton *)sender
{
    [MBProgressHUD showMessage:@"关于" hide:YES];
}
-(void)leftMenuViewDidClickedLogout:(UIButton *)sender
{
    [MBProgressHUD showMessage:@"退出" hide:YES];
}

#pragma mark - 初始化数据
-(void)setupView
{
    self.title = @"泰达时尚家园";
    
    self.view.backgroundColor = RGBColor(238, 238, 238, 1.0);;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
}
/**
 *  初始化数据
 */
-(void)setupBeginData
{
    __weak typeof(self)weakSelf = self;
    //轮播图
    NSString* path =  [Utils  BaseUrlOfApi:@"ad-list"];
    
    [SlideModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
        return @{
                 @"ID" : @"id"
                 };
    }];
    [XXNetRequest POST:path params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
            weakSelf.headerView.dataArray = [SlideModel mj_objectArrayWithKeyValuesArray:responseObject[@"result"]];

        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    //获取天气
    NSString *httpArg = @"citypinyin=tianjin";
    [self request: WeatherURL withHttpArg: httpArg];
    
}

-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    
    __weak typeof(self) weakSelf = self;
    
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue:WeatherAPIKey forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   if (responseCode == 200) {
                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                       weakSelf.headerView.weather = [WeatherModel mj_objectWithKeyValues:dict[@"retData"]];
                                       
                                   }
                               }
                           }];
}

/**
 *  点击轮播图
 */
-(void)collectionViewDidClickSlide:(UIView *)sender
{
    if (sender.tag == 999) {
        return;
    }
    SlideModel *slide = self.headerView.dataArray[sender.tag-100];
    
    XXWebViewController* browser = [[XXWebViewController alloc] init];
    browser.URL = slide.adUrl;
    [self.navigationController pushViewController:browser animated:YES];
}




#pragma mark - UICollectionView Header
//返回 Header的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(Screen_W_, 170.0f);
}

//获取Header
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *CellIdentifier = @"CollectionHeaderView";
    //从缓存中获取 Headercell
    CollectionHeaderView *header = (CollectionHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    header.delegate = self;
    self.headerView = header;
    
    return header;
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return self.dataArray.count + 3;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

        static NSString * CellIdentifier = @"MainCollectionViewCell";
        MainCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        
        cell.delegate = self;
        MainCollectionViewModel * model;
        if (indexPath.row == 0 ) {
            model = [[MainCollectionViewModel alloc] initWithTitle:@"智能摄像头" url:nil iconUrl:@"camera_icon" type:CollectionTypeModule module:@"LiveListTVC" ID:1];
            
        }
        else if(indexPath.row == 1)
        {
            model = [[MainCollectionViewModel alloc] initWithTitle:@"电视直播" url:nil iconUrl:@"tv_transmission_icon" type:CollectionTypeModule module:@"LiveListTVC" ID:2];
        }
        else if(indexPath.row == self.dataArray.count + 2)
        {
            model = [[MainCollectionViewModel alloc] initWithTitle:nil url:nil iconUrl:nil type:CollectionTypeAdd module:@"FunctionListVC" ID:self.dataArray.count - 1];
        }
        else
        {
            FunctionItem* item = self.dataArray[indexPath.row - 2];
            
            model = [[MainCollectionViewModel alloc] initWithTitle:item.name url:item.url iconUrl:item.iconUrl type:CollectionTypeWeb module:nil ID:item.ID];
        }
        cell.model = model;
        
        
        if(CellState == CellStateNormal){
            cell.deleteButton.hidden = true;
        }else{
            if (indexPath.row == self.dataArray.count + 2 || indexPath.row == 0 || indexPath.row == 1){
                cell.deleteButton.hidden = true;
            }else{
                cell.deleteButton.hidden = false;
            }
        }
        return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat singleWidth = (Screen_W_ - 30)/2.0;
    return CGSizeMake(singleWidth, 150);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{

    return UIEdgeInsetsMake(10, 10, 10, 10);
}



#pragma mark - Delegate
-(void)collectionDidClicked:(MainCollectionViewCell*)cell
{
    //删除状态时 ，恢复正常
    if(CellState == CellStateDelete)
    {
        CellState = CellStateNormal;
        [self.collectionView reloadData];
    }
    else
    {
        if (cell.model.type == CollectionTypeWeb) {
            XXWebViewController * web = [[XXWebViewController alloc] init];
            web.URL = cell.model.url;
            [self.navigationController pushViewController:web animated:YES];
        }
        else
        {
            Class className = NSClassFromString(cell.model.module);
            UIViewController * vc = [[className alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }

}
-(void)collectionDidLongPressed:(MainCollectionViewCell*)cell
{
    if (cell.model.type == CollectionTypeAdd) {
        return;
    }
    //从正常状态变为可删除状态；
    if (CellState == CellStateNormal) {
        CellState = CellStateDelete;
        //循环遍历整个CollectionView；
        for(MainCollectionViewCell *cell in self.collectionView.visibleCells){
            
            NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
            //除最后一个cell外都显示删除按钮；
            if (indexPath.row != self.dataArray.count + 2 && indexPath.row != 0 && indexPath.row != 1 ){
                [cell.deleteButton setHidden:false];
            }
        }
    }
    else if (CellState == CellStateDelete){
        CellState = CellStateNormal;
    }
    [self.collectionView reloadData];
}
-(void)collectionDidClickedDeleteButton:(MainCollectionViewCell*)cell
{
    NSIndexPath * path = [self.collectionView indexPathForCell:cell];
    
    [self.dataArray removeObjectAtIndex:path.row - 2];
    
    [CacheTool saveUserFunctionCategory:self.dataArray];
    
    [self.collectionView reloadData];
}

#pragma mark - Lazy Initialization

-(UICollectionView *)collectionView
{
    if (_collectionView == nil) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];

        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = RGBColor(238, 238, 238, 1.0);
        
        [_collectionView registerNib:[UINib nibWithNibName:@"MainCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"MainCollectionViewCell"];

        [_collectionView registerClass:[CollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CollectionHeaderView"];
        
        [self.view addSubview:_collectionView];

        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _collectionView;
}

-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithArray:[CacheTool loadUserFunctionCategory]];
    }
    return _dataArray;
}

#pragma mark - View Life Cycle
-(void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(functionCategoryChanged:) name:kUserFunctionCategoryChange object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*
 *  更新
 */
-(void)functionCategoryChanged:(NSNotification*)notification
{
    self.dataArray = [NSMutableArray arrayWithArray:[CacheTool loadUserFunctionCategory]];
    
    [self.collectionView reloadData];
}

#pragma mark - Slide Navi
- (BOOL)slideNavigationControllerShouldDisplayLeftMenu
{
    return YES;
}
@end
